/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Ventas_Productos.java
 *
 * Created on 28-feb-2011, 20:17:20
 */
package puntoventa;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.*;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author gadiaz3
 */
public class Carrito extends javax.swing.JFrame {

    private final DefaultTableModel modelo;

    /** Creates new form Ventas_Productos */
    public Carrito() {
        initComponents();
        this.setLocationRelativeTo(this);
        modelo = (DefaultTableModel) this.tableAgrega.getModel();
        mostrarTabla();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        nomField = new javax.swing.JTextField();
        BuscarB = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableAgrega = new javax.swing.JTable();
        AgregarB = new javax.swing.JButton();
        tipoBox = new javax.swing.JComboBox();
        Label2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        BuscarB.setText("Buscar");
        BuscarB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BuscarBActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N
        jLabel4.setText("Agregar Productos al Carrito");

        tableAgrega.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Nombre", "Proveedor", "Precio", "Stock"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tableAgrega);

        AgregarB.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        AgregarB.setText("Agregar");
        AgregarB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AgregarBActionPerformed(evt);
            }
        });

        tipoBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ID", "Nombre", "Proveedor" }));
        tipoBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tipoBoxActionPerformed(evt);
            }
        });

        Label2.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N
        Label2.setText("2:");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(204, 204, 204));
        jLabel1.setText("De clic en su articulo deseado y Agregue.");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                    .add(tipoBox, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .add(nomField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 114, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(BuscarB, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 119, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(AgregarB, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .add(layout.createSequentialGroup()
                                .add(58, 58, 58)
                                .add(Label2)
                                .add(7, 7, 7)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                    .add(jLabel4)
                                    .add(jLabel1))))
                        .addContainerGap(13, Short.MAX_VALUE))
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 392, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jLabel4)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabel1)
                        .add(3, 3, 3))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, Label2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createSequentialGroup()
                        .add(tipoBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(nomField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(BuscarB)))
                    .add(AgregarB, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 194, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        Ventas_Carrito v = new Ventas_Carrito();
        v.setVisible(true);
        v.getID();
    }//GEN-LAST:event_formWindowClosed

    private void AgregarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AgregarBActionPerformed
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }
        int n1;
        String n = JOptionPane.showInputDialog("Cantidad: ");
        int idp = tableAgrega.getSelectedRow();
        String id = (String) tableAgrega.getValueAt(idp, 0);
        String nom = (String) tableAgrega.getValueAt(idp, 1);
        String pre = (String) tableAgrega.getValueAt(idp, 3);
        int x = Integer.parseInt(pre);
        int y = Integer.parseInt(n);
        n1 = (x * y);

        System.out.println("id= " + id);
        try {
            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            Connection conexion = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/PDV", "root", "");
            java.sql.Statement st = conexion.createStatement();
            st.executeUpdate("insert into compras(ID,Nombre,Precio,Cantidad) values(" + id + ",'" + nom + "','" + n1 + "','" + n + "')");
            ResultSet rs = st.executeQuery("select stock from productos where ID="+id+"");
            rs.next();
            int cant = Integer.parseInt(rs.getString("stock"));
            System.out.println(""+cant);
            int rest = cant - y;
            System.out.println(""+rest);

            st.executeUpdate("update productos set stock ="+rest+" where id= "+id+"");

//            sql.executeUpdate("update set productos Stock="+n+" where ID="+id+"");

            conexion.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Ventas_Carrito c = new Ventas_Carrito();
        c.getID();
//        c.setVisible(true);
        if (n.compareTo("") == 0) {
            JOptionPane.showMessageDialog(null, "No ha especificado cantidad.", "Atención", JOptionPane.INFORMATION_MESSAGE);
        } else {
            //cantP = Integer.parseInt(n);
        }
        this.dispose();




    }//GEN-LAST:event_AgregarBActionPerformed

    private void BuscarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BuscarBActionPerformed
        try {
            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            Connection conexion = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/PDV", "root", "");
            Statement s = (Statement) conexion.createStatement();
            java.sql.Statement st = conexion.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM  productos where " + tipoBox.getSelectedItem() + "='" + nomField.getText() + "'");
            DefaultTableModel mod = (DefaultTableModel) tableAgrega.getModel();



            for (int x = mod.getRowCount() - 1; x > 0; x--) {
                System.out.println("contador =" + x + "");
                mod.removeRow(x);
            }

            if (mod.getRowCount() == 1) {
                mod.removeRow(0);
            }

            while (rs.next()) {

                String ID_q = rs.getString("ID");
                String nombre_q = rs.getString("nombre");
                String provee_q = rs.getString("proveedor");
                int precio_q = rs.getInt("precio");
                int stock_q = rs.getInt("stock");

                System.out.println(ID_q + nombre_q + provee_q + precio_q + stock_q);


                Object fortable[] = {ID_q, nombre_q, provee_q, precio_q, stock_q};

                mod.addRow(fortable);
            }
            System.out.println(mod.getRowCount());
            rs.close();
        } catch (SQLException ex) {
            Logger.getLogger(Buscar_Item.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_BuscarBActionPerformed

    private void tipoBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tipoBoxActionPerformed
    }//GEN-LAST:event_tipoBoxActionPerformed
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Carrito().setVisible(true);

            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AgregarB;
    private javax.swing.JButton BuscarB;
    private javax.swing.JLabel Label2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField nomField;
    private javax.swing.JTable tableAgrega;
    private javax.swing.JComboBox tipoBox;
    // End of variables declaration//GEN-END:variables

    private void mostrarTabla() {
        try {
            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            Connection conexion = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/PDV", "root", "");
            Statement s = (Statement) conexion.createStatement();
            ResultSet rs = s.executeQuery("select * from Productos");
            Object[] fila = new Object[5];
            while (rs.next()) {
                fila[0] = rs.getString("ID");
                fila[1] = rs.getString("Nombre");
                fila[2] = rs.getString("Proveedor");
                fila[3] = rs.getString("Precio");
                fila[4] = rs.getString("Stock");

                modelo.addRow(fila);
                this.tableAgrega.setModel(modelo);
            }
            conexion.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
